package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyuncs.kms.model.v20160120.ListSecretsResponse;
import com.zzyl.nursing.service.WeChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @Auther: zhaojh
 * @Date: 2025/6/3 - 06 - 03 - 15:28
 * @Description: com.zzyl.nursing.service.impl
 * @version: 1.0
 */
@Service
public class WeChatServiceImpl implements WeChatService {
    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.appSecret}")
    private String appSecrete;


    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    private static final String REQUEST_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    private static final String REQUEST_ACCESSS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    @Override
    public String getOpenId(String code) {

        HashMap<String, Object> param = getStringObjectHashMap();
        param.put("js_code", code);
        String result = HttpUtil.get(REQUEST_URL, param);

        System.out.println(result);
        HashMap bean = JSONUtil.toBean(result, HashMap.class);


        return (String) bean.get("openid");
    }

    private HashMap<String, Object> getStringObjectHashMap() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("appid", appId);
        param.put("secret", appSecrete);

        return param;
    }

    @Override
    public String getPhone(String code) {
        String access_token = getToken();
        HashMap<String, Object> param = new HashMap<>();

        param.put("code", code);
        String result = HttpUtil.post(REQUEST_PHONE_URL + access_token, JSONUtil.toJsonStr(param));

        HashMap bean = JSONUtil.toBean(result, HashMap.class);
        String phone = ((JSONObject) bean.get("phone_info")).getStr("phoneNumber");
        System.out.println(phone);

        return phone;
    }

    public String getToken() {
        HashMap<String, Object> param = getStringObjectHashMap();
        String result = HttpUtil.get(REQUEST_ACCESSS_TOKEN, param);

        HashMap bean = JSONUtil.toBean(result, HashMap.class);
        return (String) bean.get("access_token");

    }


}
